using IoTCenter.Utilities.Extensions;
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace Ganweisoft.IoTCenter.Module.MediaPlatform.Utilities
{
    public static class XmlExtensions
    {
        // 序列化方法
        public static string ToXml<T>(this T obj, Encoding encoding) where T : class
        {
            if (obj == null)
            {
                return string.Empty;
            }
            var settings = new XmlWriterSettings
            {
                Indent = true, // 缩进
                IndentChars = " ", // 使用空格作为缩进字符
                NewLineChars = Environment.NewLine, // 使用系统默认换行符
                NewLineHandling = NewLineHandling.Replace, // 替换元素内容中的换行符
                OmitXmlDeclaration = false, // false 开启xml文档声明
                Encoding = encoding
            };

            using (var memoryStream = new MemoryStream())
            {
                using (var streamWriter = new StreamWriter(memoryStream, encoding))
                {
                    using (var xmlWriter = XmlWriter.Create(streamWriter, settings))
                    {
                        var namespaces = new XmlSerializerNamespaces();
                        namespaces.Add("", "");

                        XmlSerializer serializer = new XmlSerializer(typeof(T));
                        serializer.Serialize(xmlWriter, obj, namespaces);
                    }
                }
                return encoding.GetString(memoryStream.ToArray());
            }
        }

        public static XElement ToXElement(this string xml, Encoding encoding)
        {
            if (xml.IsEmpty())
            {
                return null;
            }
            byte[] xmlBytes = encoding.GetBytes(xml);
            using var stream = new MemoryStream(xmlBytes);
            var settings = new XmlReaderSettings
            {
                DtdProcessing = DtdProcessing.Prohibit,  // 防止 XXE 注入
                XmlResolver = null,                      // 禁用外部资源解析
                CheckCharacters = false                  // 允许非标准字符（根据需要调整）
            };
            using var reader = XmlReader.Create(stream, settings);
            var doc = XDocument.Load(reader);
            if (doc == null)
            {
                return null;
            }
            return doc.Root;
        }

        public static string GetNodeValue(this XElement bodyXml, string nodeName)
        {
            if (bodyXml == null || bodyXml.IsEmpty || !bodyXml.HasElements || nodeName.IsEmpty())
            {
                return string.Empty;
            }

            var cmdTypeNode = bodyXml.Element(nodeName);
            if (cmdTypeNode == null)
            {
                return string.Empty;
            }

            return cmdTypeNode.Value;
        }
    }
}
